package com.qf.air.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.air.config.RabbitMQConfig;
import com.qf.air.service.SearchService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author zjw
 * @description 监听air_queue中的消息，将内容同步到ES中
 * @date 2021/11/9 15:28
 */
@Component
public class AirListener {

    @Autowired
    private SearchService searchService;

    @Autowired
    private ObjectMapper mapper;

    @RabbitListener(queues = RabbitMQConfig.AIR_QUEUE)
    public void consume(String json, Channel channel, Message message) throws IOException {
        //1. 获取生产者携带的RoutingKey
        String routingKey = message.getMessageProperties().getReceivedRoutingKey();

        //2. 确定操作的业务
        switch (routingKey){
            case "air.save":
                // 添加数据到ES
                searchService.add(mapper.readValue(json, Map.class));
                break;
            case "air.delete":
                // 根据id删除ES中的数据
                searchService.delete(mapper.readValue(json, String.class));
                break;
            case "air.update":
                // 根据id修改ES中的数据
                break;
            default:
        }

        //3. 手动ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
